//
//  FrontCameraViewController.swift
//  CalligraphyUniversal
//
//  Created by 李雷川 on 2017/9/18.
//  Copyright © 2017年 李雷川. All rights reserved.
//

import UIKit
import FZSFCommonTools
import AVFoundation
 public class FZCameraViewController: TakePhotoBaseViewController {
    fileprivate let wrapper = Wrapper()
    override public func viewDidLoad() {
        super.viewDidLoad()

        if isRightCamera(){
            configureWrapper()
        }
        initUI()
        switchCameraButton.isHidden = !isCanSwitchCamera
 
    }
    override public func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        start()
    }
    
    override open func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        stop()
    }
    
    override public func viewDidAppear(_ animated: Bool) {
        if isRightCamera() == false{
            showAlertController(title: "无法访问相机", message:"请在\"设置-隐私\"选项中，允许访问你的相机",confirm:"去设置",cancel:"知道了", parentController: self, cofirmClosure: {
                UIApplication.shared.openURL(NSURL.init(string:UIApplication.openSettingsURLString)! as URL)
            }, cancelClosure: {
                self.dismiss(animated: true, completion: nil)
            })
        }
    }
    
    override func startGeneragteImage(){
        stop()
        guard let image = wrapper.generateImage() else{
            start()
            generateImageFaild()
            return
        }
        var imageOrientation = UIImage.Orientation.up
        switch (UIApplication.shared.statusBarOrientation) {
        case .portrait:
            imageOrientation = UIImage.Orientation.right
        case .portraitUpsideDown:
            imageOrientation = UIImage.Orientation.left
        case .landscapeLeft:
            imageOrientation = UIImage.Orientation.down
        case .landscapeRight:
            break
        case .unknown:
            debugPrint("")
        @unknown default:
            fatalError()
        }
        let resultImage =  UIImage(cgImage: (image.cgImage!), scale:UIScreen.main.scale, orientation:imageOrientation)
        generateImageSuccess(image: resultImage)

    }
    
    func start(){
        wrapper.start()
    }
    
    func stop(){
        wrapper.stop()
    }
    
    func configureWrapper(){
        wrapper.setTargetView(view)
        wrapper.switchCameraPosition(isFrontCamera)
    }
    
    @objc override func tapSwitchCamera(sender:UIButton){
        super.tapSwitchCamera(sender: sender)
        wrapper.switchCameraPosition(isFrontCamera)
    }
}

